package com.automobile.backstage.controller;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-23 20:51
 */
@Controller
public class FileController {

    private String url = "http://localhost:8080/Smart/upload/";

    @ResponseBody
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("upload") MultipartFile[] uploads) throws IOException {
        String announceLine = "announce['title':'666','content':'22132132']";
        System.out.println("upload.....");
        //创建HttpClients实体类
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("announce", announceLine.getBytes(), ContentType.create("application/json;charset=utf-8"), null);
        for (MultipartFile upload : uploads) {
            String filename = upload.getOriginalFilename();
            builder.addBinaryBody("upload", upload.getBytes(), ContentType.create("multipart/form-data"), filename);
        }
        try {
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);

            System.out.println("=="+response.getStatusLine().getStatusCode());
            String s = response.getEntity().toString();
            System.out.println("==="+s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }

        return "success";
    }

}
